// import CryptoJS from 'crypto-js'
import moment from 'moment'
// storages
const setItem = type => (key, item) => {
  const obj = window[`${type}Storage`]
  return obj.setItem(key, JSON.stringify(item))
}
const getItem = type => (key, defaultValue, saveIfNotExist) => {
  const obj = window[`${type}Storage`]
  const savedItem = obj.getItem(key)
  if (!savedItem && saveIfNotExist) {
    setItem(type)(key, defaultValue)
  }
  try {
    if (savedItem) return JSON.parse(savedItem)
  } catch (e) {
    obj.removeItem(key)
    return defaultValue
  }
  return defaultValue
}
const removeItem = type => (key) => {
  const obj = window[`${type}Storage`]
  obj.removeItem(key)
}
const clear = type => () => {
  window[`${type}Storage`].clear()
}
export const storage = {
  local: {
    setItem: setItem('local'),
    getItem: getItem('local'),
    removeItem: removeItem('local'),
    clear: clear('local')
  },
  session: {
    setItem: setItem('session'),
    getItem: getItem('session'),
    removeItem: removeItem('session'),
    clear: clear('session')
  }
}

// cookies
export const setCookie = (cName, value, expiredays) => {
  const exdate = new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = cName + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
}
export const getCookie = name => {
  let arr
  const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  if (arr === document.cookie.match(reg)) {
    return (arr[2])
  } else {
    return null
  }
}
export const delCookie = name => {
  const exp = new Date()
  exp.setTime(exp.getTime() - 1)
  const cval = getCookie(name)
  if (cval != null) {
    document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
  }
}

// 获取url参数
export const getQueryString = name => {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  const r = window.location.search.substr(1).match(reg)
  if (r != null) {
    if (r[2].indexOf('%u') < 0) {
      r[2] = decodeURIComponent(r[2]).replace(/\\/g, '%')
    }
    return unescape(r[2])
  }
  return null
}
// 生产随机length位数数字
export const randomLenNum = (len, date) => {
  let random = ''
  random = Math.ceil(Math.random() * 1000000000000).toString().substr(0, len || 4)
  if (date) random = random + Date.now()
  return random
}

// 加密
// export const encryption = (params) => {
//   let {
//     data,
//     type,
//     param,
//     key
//   } = params
//   const result = JSON.parse(JSON.stringify(data))
//   if (type === 'Base64') {
//     param.forEach(ele => {
//       result[ele] = btoa(result[ele])
//     })
//   } else {
//     param.forEach(ele => {
//       let data = result[ele]
//       key = CryptoJS.enc.Latin1.parse(key)
//       let iv = key
//       // 加密
//       let encrypted = CryptoJS.AES.encrypt(
//         data,
//         key, {
//           iv: iv,
//           mode: CryptoJS.mode.CBC,
//           padding: CryptoJS.pad.ZeroPadding
//         })
//       result[ele] = encrypted.toString()
//     })
//   }
//   return result
// }
// 表单序列化
export const serialize = data => {
  const list = []
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&')
}
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'undefined' || time === null || time === 'null') {
    return ''
  } else if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
export function pySegSort(arr, empty) {
  if (!String.prototype.localeCompare) {
    return null
  }
  const letters = '*abcdefghjklmnopqrstwxyz'.split('')
  const zh = '阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀'.split('')
  const segs = []
  let curr
  letters.forEach((letter, i) => {
    curr = { name: letter, data: [] }
    arr.forEach(item => {
      if ((!zh[i - 1] || zh[i - 1].localeCompare(item.name, 'zh') <= 0) && item.name.localeCompare(zh[i], 'zh') === -1) {
        curr.data.push(item)
      }
    })
    if (empty || curr.data.length) {
      segs.push(curr)
      curr.data.sort(function(a, b) {
        return a.name.localeCompare(b.name, 'zh')
      })
    }
  })
  return segs
}
// 下载文件(流转换)
export function downloadFile(obj, name, suffix) {
  console.log('simida')
  // console.log(obj)
  const url = window.URL.createObjectURL(new Blob([obj]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
export function exportExcel(steam, name) {
  // var blob = new Blob([steam])
  // let elink = document.createElement('a');

  // elink.download = "download.xls";
  // elink.href = URL.createObjectURL(blob);
  // elink.click();

  // const blob = new Blob([steam], { type: 'application/octet-stream;charset=utf-8' })
  // const fileName = name + '.xls'
  // const elink = document.createElement('a')
  // elink.download = fileName
  // elink.style.display = 'none'
  // elink.href = URL.createObjectURL(blob)
  // document.body.appendChild(elink)
  // elink.click()
  // URL.revokeObjectURL(elink.href)
  // document.body.removeChild(elink)

  const content = steam
  const blob = new Blob([content])
  const fileName = name + '.xlsx'
  if ('download' in document.createElement('a')) { // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
}

export const menuTree = [
  {
    id: 1,
    url: '/data_list',
    name: '平台数据',
    show: true
  },
  {
    id: 2,
    url: '/user',
    name: '用户管理',
    children: [
      {
        url: '/user_list',
        name: '用户列表',
        id: 3
      },
      {
        url: '/user_pipe_list',
        name: '管长列表',
        id: 4
      },
      {
        url: '/user_not_list',
        name: '未捐赠用户',
        id: 5
      },
      {
        url: '/user_freeze_list',
        name: '冻结列表',
        id: 6
      }
    ]
  },
  {
    id: 7,
    url: '/team',
    name: '战队管理',
    children: [
      {
        url: '/team_apply',
        name: '申请中战队',
        id: 8
      }, {
        url: '/team_line',
        name: '公排中战队',
        id: 9
      }, {
        url: '/team_proceed',
        name: '进行中战队',
        id: 10
      }, {
        url: '/team_end',
        name: '已完成战队',
        id: 11
      }
    ]
  },
  {
    id: 12,
    url: '/rw',
    name: '提现管理',
    children: [
      {
        url: '/rw_allroval',
        name: '提现审核',
        id: 13
      },
      {
        url: '/rw_set',
        name: '提现设置',
        id: 14
      }
    ]
  },
  {
    id: 15,
    url: '/fund',
    name: '资金记录',
    children: [
      {
        url: '/fund_withdraw',
        name: '提现记录',
        id: 16
      },
      {
        url: '/fund_recharge',
        name: '充值记录',
        id: 17
      }, {
        url: '/fund_transfer',
        name: '转让金钥匙记录',
        id: 18
      },
      {
        url: '/fund_buy',
        name: '金钥匙购买记录',
        id: 19
      },
      {
        url: '/fund_detail',
        name: '划扣记录',
        id: 20
      }
    ]
  },
  {
    id: 21,
    url: '/sys',
    name: '系统管理',
    children: [
      {
        url: '/sys_notice',
        name: '系统公告',
        id: 22
      },
      // {
      //   url: "/sys_text",
      //   name: "文案设置",
      //   id: 23
      // },
      {
        url: '/sys_service',
        name: '在线客服',
        id: 24
      },
      {
        url: '/sys_config',
        name: '系统设置',
        id: 25
      }
    ]
  },
  {
    id: 26,
    url: '/auth',
    name: '权限管理',
    show: true
  }
]

export function formatTime(time) {
  return (time && moment(time).format('YYYY-MM-DD HH:mm:ss') || '')
}
